package com.guangzhi.weijianzhi.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.Set;
import java.util.logging.Level;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.ExifInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.text.Html;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.text.style.StyleSpan;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Adapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.PopupWindow.OnDismissListener;

import com.guangzhi.weijianzhi.R;
import com.guangzhi.weijianzhi.context.WeijianzhiApplication;
import com.haarman.listviewanimations.swinginadapters.prepared.ScaleInAnimationAdapter;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

/**
 * 公共的工具类
 * 
 * @author 时间转换 判断网络 发送警告到服务器 导出数据流 检查一个字符串是否是整数。该函数将避免NumberFormat异常。
 *         求一个数的模数,该函数通常用来循环获得0-length的索引. 计算方差 临时保存图片
 *         将长字符从截取剩下的用more代替,more为空则用省略号代替 获取veritoincode
 */
public class Misc {
	/**
	 * 是否连接WIFI
	 */
	public static boolean isWifiConnected(Context context) {
		ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo wifiNetworkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		if (wifiNetworkInfo.isConnected()) {
			return true;
		}

		return false;
	}


	/**
	 * get fit width for different resolution,input param is width for 720
	 * 
	 * @param width
	 */
	public static int getFitWidth(Context context, int inwidth) {
		if (context == null)
			return inwidth;
		int screenwidth = getResolution(context)[0];
		return (inwidth * screenwidth) / 720;
	}

	/**
	 * get fit width for different resolution,input param is width for 1180
	 * 
	 * @param width
	 */
	public static int getFitHeight(Context context, int inheight) {
		if (context == null)
			return inheight;
		int screenheight = getResolution(context)[1];
		return (inheight * screenheight) / 1280;
	}

	/**
	 * get resolution
	 * 
	 * @param context
	 * @return
	 */
	public static int[] getResolution(Context context) {
		int resolution[] = new int[2];
		// DisplayMetrics dm = new DisplayMetrics();
		// getWindowManger(context).getDefaultDisplay().getMetrics(dm);
		Display display = getWindowManger(context).getDefaultDisplay();
		resolution[0] = display.getWidth();
		resolution[1] = display.getHeight();
		return resolution;
	}

	/**
	 * get WindowManager
	 */
	public static WindowManager getWindowManger(Context context) {
		if (context == null)
			return null;
		WindowManager windowManager = null;
		windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
		return windowManager;
	}

	/**
	 * @param object
	 *            Toast显示提示
	 */
	public static void alert(Object object) {
		try {
			Toast toast = Toast.makeText(WeijianzhiApplication.getInstance(), Misc.toString(object), Toast.LENGTH_SHORT);
			toast.show();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * toast居中显示
	 * 
	 * @param id
	 */
	public static void alertCenter(Object object) {
		try {
			Toast toast = Toast.makeText(WeijianzhiApplication.getInstance(), Misc.toString(object), Toast.LENGTH_SHORT);
			toast.setGravity(Gravity.CENTER, 0, 0);
			toast.show();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void alert(int id) {
		try {
			Toast toast = Toast.makeText(WeijianzhiApplication.getInstance(), Misc.getStrValue(id), Toast.LENGTH_SHORT);
			toast.show();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * toast居中显示
	 * 
	 * @param id
	 */
	public static void alertCenter(int id) {
		try {
			Toast toast = Toast.makeText(WeijianzhiApplication.getInstance(), Misc.getStrValue(id), Toast.LENGTH_SHORT);
			toast.setGravity(Gravity.CENTER, 0, 0);
			toast.show();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void logThreadId(String prefix) {

		log(prefix, "log thread", Thread.currentThread().getId());
	}

	// 调试用函数开始
	public static void alertDump(Object... objects) {
		// if (APIV1.isDebug()) {
		alert(dumpObject(objects));
		// }
	}

	public static void log(RectF rect) {
		// if (APIV1.isDebug()) {
		Log.v("rect", Misc.concat(rect.left, "-", rect.right, ",", rect.top, "-", rect.bottom));
		// }
	}

	public static void log(Rect rect) {
		// if (APIV1.isDebug()) {
		Log.v("rect", Misc.concat(rect.left, "-", rect.right, ",", rect.top, "-", rect.bottom));
		// }
	}

	public static void log(Object... objects) {
		if (true) {
			Log.w("test", dumpObject(objects));
		}
	}

	public static void debug(Object... objects) {
		// if (APIV1.isDebug()) {
		Log.v("System.err", dumpObject(objects));
		// (new Exception()).printStackTrace();
		// }
	}

	public static String dumpObject(Object... objects) {
		String result = new String();

		ArrayList<String> resultArr = new ArrayList<String>();

		if (objects == null) {
			result = "null";
		} else {
			for (Object object : objects) {
				resultArr.add(dumpSingleObject(object));
			}
			result = Misc.quoteString(Misc.join(resultArr.toArray()), "[", "]");
		}

		return result;
	}

	/**
	 * @return
	 */
	private static String dumpSingleObject(Object object) {
		String result = new String();
		if (object == null) {
			result = "null";
		} else {
			String className = object.getClass().getName();
			String value = object.toString();
			result = className + ":" + value;
		}
		return result;
	}

	private static Resources resources;

	// public static void alert(final String value) {
	// WeijianzhiApplication.getActivity().runOnUiThread(new Runnable() {
	//
	// @Override
	// public void run() {
	// Toast.makeText(
	// WeijianzhiApplication.getActivity()
	// .getApplicationContext(), value,
	// Toast.LENGTH_SHORT).show();
	// }
	// });
	// }


	/**
	 * 时间转换 输入一个string 输出 yyyy/MM/dd HH:mm
	 */
	public static String getDateFromStr(String strTime) {
		String date;
		if (strTime != null && !"".equals(strTime)) {

			long updateTime = Long.parseLong(strTime);
			SimpleDateFormat dateformat1 = new SimpleDateFormat("yyyy/MM/dd HH:mm");
			date = dateformat1.format(new Date(updateTime * 1000));
			return date;
		} else {
			return "";
		}
	}

	/**
	 * 检查是否连接网络
	 * 
	 * @param context
	 * @return
	 */
	public static boolean isNetworkConnected() {
		ConnectivityManager mConnectivityManager = (ConnectivityManager) WeijianzhiApplication.getInstance().getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
		if (mNetworkInfo != null) {
			return mNetworkInfo.isAvailable();
		}
		return false;
	}

	/**
	 * Check network connection which is connected.
	 * 
	 * <p>
	 * Usually, we need to check the network connection is connected, currently
	 * the given type is either Wifi or Mobile. Network state is available does
	 * not mean that the network connection is connected. So just check the
	 * network state available is the wrong way.
	 * 
	 * <p>
	 * <Font color=red>Note</Font>:This method can only be run on a real device.
	 * 
	 * @return if return true, the network connection has connected; else return
	 *         false.
	 * @throws Exception
	 *             Any exceptions should ensure that this method will always
	 *             return a value before the exception thrown. But in this
	 *             method, it just catch, does not throw.
	 * 
	 * @author Damet Liu
	 * @since 2013-12-1 17:00:00 V1.0.0
	 * 
	 * @see {@link ConnectivityManager#getAllNetworkInfo()}
	 * @see {@link NetworkInfo#getState()}
	 * @see {@link State}
	 */
	public boolean isNetworkOnline() {
		boolean status = false;
		try {
			// Check all NetworkInfo state which has been connected.
			// If not find the one is connected, always return false.
			ConnectivityManager connectivityManager = (ConnectivityManager) WeijianzhiApplication.getInstance().getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo[] networkInfos = connectivityManager.getAllNetworkInfo();
			for (int index = 0; index < networkInfos.length; index++) {
				NetworkInfo netInfo = networkInfos[index];
				if ((netInfo != null) && netInfo.isConnected()) {
					status = true;
					;
				}
			}
		} catch (Exception e) {
			// Only print the exception message and stack trace,
			// because this method must return a value to caller.
			e.printStackTrace();
		}
		return status;
	}


	/**
	 * @return 导出数据流
	 */
	public static BufferedInputStream exportData(String dbName) {
		try {
			// 当前程序路径
			String path = WeijianzhiApplication.getInstance().getApplicationContext().getFilesDir().getAbsolutePath();
			path = path + "/../databases/" + dbName;
			File file = new File(path);
			FileInputStream inStream = new FileInputStream(file);
			BufferedInputStream in = new BufferedInputStream(inStream);
			return in;
		} catch (FileNotFoundException e) {
			return null;
		}
	}

	/**
	 * @param in
	 *            导入数据流
	 */
	public static void importData(BufferedInputStream in, String dbName) {
		try {
			// 当前程序路径
			String path = WeijianzhiApplication.getInstance().getFilesDir().getAbsolutePath();
			path = path + "/../databases/";
			File file = new File(path);
			file.mkdirs();
			path += dbName;
			file = new File(path);
			file.createNewFile();
			FileOutputStream outStream = new FileOutputStream(file);
			BufferedOutputStream out = new BufferedOutputStream(outStream);
			int c;
			while ((c = in.read()) >= 0) {
				out.write(c);
			}
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 检查一个字符串是否是整数。该函数将避免NumberFormat异常。
	 * 
	 * @param num
	 *            需要检查的字符串
	 * @return 返回true表示是一个整数;如果字符串为为空，或者不符合规则返回false.
	 * 
	 * @see {@link NumberFormatException}
	 */
	public static final boolean checkNumberFormat(String num) {
		if (TextUtils.isEmpty(num))
			return false;
		return num.matches("-[0-9]+|[0-9]+");
	}

	/**
	 * 求一个数的模数,该函数通常用来循环获得0-length的索引.
	 * <p>
	 * <code>for example:</br>
	 * <pre>
	 * final int divisor = 4;
	 * for(int dividend = -9; dividend < 10; dividend ++)
	 * {
	 *     System.out.println(computeRemainder(dividend, divisor));
	 * }
	 * </pre></code>
	 * 
	 * 你将只能获得0-3的数。
	 * 
	 * @param dividend
	 *            被除数
	 * @param divisor
	 *            除数
	 * @return 模数
	 */
	public static final int computeRemainder(int dividend, int divisor) {
		final int modulus = dividend % divisor;
		if (modulus < 0)
			return modulus + divisor;
		else
			return modulus;
	}

	public static final <T> T J2O(JSONObject object, Class<T> clazz) {
		T result = null;
		try {
			result = clazz.newInstance();

		} catch (IllegalAccessException e) {
			e.printStackTrace();
			return null;
		} catch (InstantiationException e) {
			e.printStackTrace();
			return null;
		}

		Field[] fields = clazz.getDeclaredFields();
		for (Field field : fields) {
			final String name = field.getName();
			field.setAccessible(true);
			if (object.has(name)) {
				try {
					field.set(result, object.getString(name));
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
					return null;
				} catch (IllegalAccessException e) {
					e.printStackTrace();
					return null;
				} catch (JSONException e) {
					e.printStackTrace();
					return null;
				}
			}
		}

		return result;
	}

	public static String quoteString(Object object, String left, String right) {
		return left.concat(object.toString()).concat(right);
	}

	public static String concat(Object... objects) {

		String str = new String();
		if (objects != null) {
			for (Object object : objects) {
				if (object != null) {
					try {
						str = str.concat(object.toString());
					} catch (Exception e) {
					}
				}
			}
		}
		return str;
	}

	public static <T> String join(Set<T> list) {
		return join(list.toArray(), ",");
	}

	public static String join(Object[] objects) {
		return join(objects, ",");
	}

	public static String join(Object[] objects, String glue) {
		int k = objects.length;
		if (k == 0)
			return "";
		StringBuilder out = new StringBuilder();
		out.append(objects[0]);
		for (int x = 1; x < k; ++x)
			out.append(glue).append(objects[x]);
		return out.toString();
	}

	/**
	 * 根据名称返回字符资源的id
	 * 
	 * @return 正确返回id值，异常返回－1
	 */
	public static int getStringId(String fieldName) {
		try {
			return getResourceId(fieldName, "string");
		} catch (Exception e) {
			e.printStackTrace();
			return -1;
		}
	}

	public static int getResourceId(String fieldName, String type) {
		try {
			return getResources().getIdentifier(fieldName, type, "com.guangzhi.weijianzhi");
		} catch (Exception e) {
			e.printStackTrace();
			return -1;
		}
	}

	public static void setUnderLine(TextView textView, String text1, String text2) {
		textView.setText(Html.fromHtml(text1 + "<u>" + text2 + "</u>"));
	}

	public static String toString(Object object) {
		String result = "错误：null";
		if (object != null) {
			result = object.toString();
		}
		return result;
	}

	/**
	 * 计算方差
	 * 
	 * @param nums
	 * @return
	 */
	public static double calD(ArrayList<Integer> nums) {
		double sum = 0;
		double n = nums.size();
		double d = 0;
		if (n > 0) {
			// 求和
			for (double num : nums) {
				sum += num;
			}
			double u = (double) sum / (double) nums.size();

			double temp = 0;
			for (double num : nums) {
				temp += (num - u) * (num - u);
			}

			d = Math.sqrt((double) temp / (double) n) / u;

		}

		return d;
	}

	public static boolean isInt(Field field) {
		return field.getType().getSimpleName().equals("int");
	}

	public static int getInt(Object object, int defaultValue) {

		String str = "";
		if (object != null) {
			str = object.toString();

		}
		return parseInt(str, defaultValue);
	}

	public static long getLong(Object object, long defaultValue) {
		String str = "";
		if (object != null) {
			str = object.toString();

		}
		return parseLong(str, defaultValue);
	}

	public static long getLong(JSONObject jsonObject, String name, long defaultValue) {
		long result = defaultValue;
		try {
			if (jsonObject != null && jsonObject.has(name)) {
				result = jsonObject.getLong(name);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	public static int parseInt(String object, int defalult) {
		return (int) parseDouble(object, defalult);
	}

	public static float parseFloat(String object, float defalult) {
		return (float) parseDouble(object, defalult);
	}

	public static long parseLong(String object, long defalult) {
		return (long) parseDouble(object, defalult);
	}

	public static double parseDouble(String object, double defalult) {
		double result = defalult;
		if (object != null && object.length() > 0) {
			try {
				result = Double.parseDouble(object);
			} catch (Exception e) {

			}
		}
		return result;
	}

	public static int getInt(JSONObject jsonObject, String name, int defaultValue) {
		int result = defaultValue;
		try {
			if (jsonObject != null && jsonObject.has(name)) {
				result = jsonObject.getInt(name);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;

	}

	/**
	 * @param string
	 *            string以逗号分隔返回string的hashset
	 * @return
	 */
	public static HashSet<String> parseKeys(String string) {
		HashSet<String> keywords = new HashSet<String>();
		if (string != null) {
			for (String key : string.split(",")) {
				keywords.add(key);
			}
		}
		return keywords;
	}

	/**
	 * @param week
	 *            calendar.day
	 * @return 星期几
	 */
	public static String getFriendlyWeekStr(int week) {
		String result = "";
		switch (week) {
		case Calendar.MONDAY:
			result = "一";
			break;
		case Calendar.TUESDAY:
			result = "二";
			break;
		case Calendar.WEDNESDAY:
			result = "三";
			break;
		case Calendar.THURSDAY:
			result = "四";
			break;
		case Calendar.FRIDAY:
			result = "五";
			break;
		case Calendar.SATURDAY:
			result = "六";
			break;
		case Calendar.SUNDAY:
			result = "日";
			break;

		}

		return result;

	}

	/**
	 * 从数组里随机的获取一个
	 * 
	 * @param <T>
	 * @param list
	 * @return
	 */
	public static <T> T getRandOne(T[] list) {
		T result = null;
		if (list != null && list.length > 0) {
			int count = list.length;
			// int index = count - 1;
			int index = (int) (Math.random() * count);
			result = list[index];
		}
		return result;
	}

	public static <T> T getRandOne(List<T> arrayList) {
		T result = null;
		if (arrayList != null && arrayList.size() > 0) {
			int count = arrayList.size();
			int index = count - 1;
			index = (int) (Math.random() * index);
			result = arrayList.get(index);
		}
		return result;
	}

	public static <T> T getRandOne(Set<T> sets) {
		T result = null;
		if (sets != null) {
			int size = sets.size();
			int random = new Random().nextInt(size);
			int i = 0;
			for (T item : sets) {
				if (i == random) {
					result = item;
					break;
				}
				i = i + 1;
			}
		}
		return result;
	}

	@SuppressWarnings("unchecked")
	public static <T> ArrayList<T> getRands(ArrayList<T> arrayList, int num) {
		ArrayList<T> result = new ArrayList<T>();
		if (arrayList != null && arrayList.size() > 0) {
			num = Math.min(num, arrayList.size());
			arrayList = (ArrayList<T>) arrayList.clone();

			for (int i = 0; i < num; i++) {
				int randIndex = (int) (Math.random() * (arrayList.size() - 1));
				result.add(arrayList.get(randIndex));
				arrayList.remove(randIndex);
			}
		}
		return result;
	}

	public static float getDenisty() {
		DisplayMetrics screenDpi = new DisplayMetrics();
		((Activity) WeijianzhiApplication.getInstance()).getWindowManager().getDefaultDisplay().getMetrics(screenDpi);
		return screenDpi.density;
	}

	/**
	 * 
	 * @param objects
	 * @param glue
	 * @param left
	 * @param right
	 * @return
	 */
	public static String joinWithQuote(Object[] objects, String glue, String left, String right) {
		int k = objects.length;
		if (k == 0)
			return null;
		StringBuilder out = new StringBuilder();
		out.append(quoteString(objects[0], left, right));
		for (int x = 1; x < k; ++x)
			out.append(glue).append(quoteString(objects[x], left, right));
		return out.toString();
	}

	/**
	 * @param object
	 *            判断对象是否为空，字符从为“”，long跟int是否为0
	 * @return
	 */
	public static boolean isEmptyObject(Object object) {
		boolean isEmpty = false;
		if (object == null) {
			isEmpty = true;
		} else {
			if (object.getClass().equals(String.class)) {
				if (object.toString().length() == 0) {
					isEmpty = true;
				}
			} else if (object.getClass().equals(Integer.class) || object.getClass().equals(Long.class)) {
				if (object.equals(0)) {
					isEmpty = true;
				}
			}
		}
		return isEmpty;
	}

	public static boolean isTrue(Object object) {
		return isTrue(object, true);
	}

	public static boolean isTrue(Object object, Object compareTo) {
		if (object == null) {
			return false;
		} else if (object.equals(compareTo)) {
			return true;
		} else {
			return false;
		}
	}

	public static <K, V extends Comparable<V>> List<Entry<K, V>> sortedByValue(Map<K, V> map, Comparator<Entry<K, V>> comparator) {
		List<Entry<K, V>> list = new ArrayList<Entry<K, V>>();
		list.addAll(map.entrySet());
		Collections.sort(list, comparator);

		return list;
	}

	/**
	 * @param v
	 * @param width
	 * @param height
	 * @return 获取view固定宽高的图像
	 */
	public static Bitmap getViewCache(View v, int width, int height) {
		Bitmap b = null;
		if (v != null) {
			try {

				v.setDrawingCacheEnabled(true);
				v.measure(width == 0 ? MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED) : width, height == 0 ? MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED) : height);
				v.layout(0, 0, width == 0 ? v.getMeasuredWidth() : width, height == 0 ? v.getMeasuredHeight() : height);
				v.buildDrawingCache(true);
				if (v.getDrawingCache() != null) {
					b = Bitmap.createBitmap(v.getDrawingCache());
				}
				v.setDrawingCacheEnabled(false); // clear drawing cache
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return b;
	}


	/**
	 * @return 精简版缓存路径
	 */
	private static String getCacheDir() {
		File cacheDir = new File(concat(getSDcardRootPath(), "/", ".cache/dayima/concept/"));
		if (!cacheDir.exists()) {
			cacheDir.mkdirs();
		}
		return cacheDir.getAbsolutePath();
	}

	/**
	 * @return 精简版crash路径
	 */
	public static String getCrashReportDir() {
		File cacheDir = new File(concat(getSDcardRootPath(), "/", ".cache/dayima/concept/crash/"));
		if (!cacheDir.exists()) {
			cacheDir.mkdirs();
		}
		return cacheDir.getAbsolutePath();
	}

	public static String getSDcardRootPath() {
		return Environment.getExternalStorageDirectory().getAbsolutePath();
	}

	public static String getDarenShareImagePath(View view, String type) {
		String darenShareImagePath = "";
		Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight() + 50, android.graphics.Bitmap.Config.ARGB_8888);
		Canvas canvas = new Canvas(bitmap);
		// 绘制背景
		canvas.drawColor(Color.WHITE);
		// 绘制元素
		view.draw(canvas);
		// 绘制logo
		drawLogo(canvas, type);
		// 保存文件，并返回文件路径
		darenShareImagePath = saveImageToCache(bitmap);
		return darenShareImagePath;
	}

	/**
	 * 在左下角绘制logo
	 * 
	 * @param canvas
	 */
	public static void drawLogo(Canvas canvas, String type) {
		float heightParent = canvas.getHeight();

		float heightWrap = dip2px(40);
		float heightLogo = dip2px(20);
		float heightText = dip2px(12);

		float leftMargin = dip2px(10);

		canvas.save();
		canvas.translate(leftMargin, 0);
		// 绘制logo
		Bitmap logoBitmap = BitmapFactory.decodeResource(WeijianzhiApplication.getInstance().getResources(), android.R.layout.select_dialog_item);
		Matrix logoMatrix = new Matrix();
		Paint logoPaint = new Paint();
		logoPaint.setAntiAlias(true);
		float scale = heightLogo / (float) logoBitmap.getHeight();
		logoMatrix.postScale(scale, scale, 0, 0);
		logoMatrix.postTranslate(0, heightParent - heightWrap + (heightWrap - heightLogo) / 2);

		canvas.drawBitmap(logoBitmap, logoMatrix, logoPaint);

		// 绘制文字
		TextPaint textPaint = new TextPaint();
		textPaint.setAntiAlias(true);
		textPaint.setTextSize(heightText);
		String text = "  " + type + "  by 微兼职";

		// 垂直居中高度修正
		// float fix = Misc.dip2px(2);
		/*
		 * canvas.drawText(text, heightLogo, heightParent - heightWrap +
		 * heightText - fix + (heightWrap - heightText) / 2, textPaint);
		 */

		canvas.drawText(text, heightLogo, heightParent - heightText, textPaint);

		canvas.restore();
	}

	/**
	 * 临时保存图片
	 * 
	 * @param bitmap
	 * @return 图片路径
	 */
	public static String saveImageToCache(Bitmap bitmap) {
		String result = null;
		try {
			if (checkSDCard()) {
				String cacheDir = getCacheDir();
				if (cacheDir != null) {
					File cacheFile = new File(getCacheDir(), "com.guangzhi.weijianzhi.imageShare.png");
					cacheFile.deleteOnExit();
					OutputStream out = new BufferedOutputStream(new FileOutputStream(cacheFile));
					bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
					result = cacheFile.getPath();
					// 文件关闭
					out.flush();
					out.close();

				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 检测是否有sd卡
	 * 
	 * @return
	 */
	public static boolean checkSDCard() {
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 分享文本信息
	 * 
	 * @param title
	 *            分享标题
	 * @param content
	 *            分享内容
	 */
	public static void share(String content) {
		Intent intent = new Intent("android.intent.action.SEND");
		intent.setType("text/plain");
		// intent.putExtra(Intent.EXTRA_SUBJECT, title);
		intent.putExtra(Intent.EXTRA_TEXT, content);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		WeijianzhiApplication.getInstance().startActivity(Intent.createChooser(intent, "分享到"));
	}

	/**
	 * 分享带图片的信息
	 * 
	 * @param title
	 *            分享标题
	 * @param content
	 *            分享内容
	 * @param imgPath
	 *            图片路径，如"file:////sdcard//8.png"，注意分享结束后该文件可能被删除，所以请使用临时文件，
	 *            并分享结束后判断并删除该临时文件
	 */
	public static void share(String content, String imgPath) {
		Intent intent = new Intent("android.intent.action.SEND");

		intent.setType("image/*");
		// intent.setType("image/png");
		// intent.putExtra(Intent.EXTRA_SUBJECT, title);
		intent.putExtra(Intent.EXTRA_TEXT, content);
		intent.putExtra("sms_body", content);
		intent.putExtra(Intent.EXTRA_STREAM, Uri.parse(imgPath));
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		WeijianzhiApplication.getInstance().startActivity(Intent.createChooser(intent, "分享到"));
	}

	public static Drawable getDrawable(int id) {

		return getResources().getDrawable(id);
	}

	/**
	 * 获取resource
	 * 
	 * @return
	 */
	public static synchronized Resources getResources() {
		if (resources == null) {
			resources = WeijianzhiApplication.getInstance().getResources();
		}
		return resources;
	}

	/**
	 * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
	 */
	public static int dip2px(float dpValue) {
		final float scale = WeijianzhiApplication.getInstance().getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}

	public static int dip2px(Double dpValue) {
		final float scale = WeijianzhiApplication.getInstance().getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}

	/**
	 * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
	 */
	public static int px2dip(float pxValue) {
		final float scale = WeijianzhiApplication.getInstance().getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}

	public static int getPackageVerionCode() throws NameNotFoundException {
		int infoVersion;
		PackageInfo info = WeijianzhiApplication.getInstance().getPackageManager().getPackageInfo(WeijianzhiApplication.getInstance().getPackageName(), 0);
		infoVersion = info.versionCode;
		return infoVersion;
	}

	/**
	 * 检查新版本
	 * 
	 * 
	 */

	/**
	 * @param color
	 * @param relative
	 * @param str
	 * @return
	 */
	public static CharSequence getSpan(int color, float relative, CharSequence str) {
		SpannableStringBuilder sb = new SpannableStringBuilder(str);
		sb.setSpan(new ForegroundColorSpan(color), 0, sb.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
		if (relative != 1f) {
			sb.setSpan(new RelativeSizeSpan(relative), 0, sb.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
		}
		return sb;
	}

	/**
	 * @param color
	 * @param relative
	 * @param typeFace
	 * @param str
	 * @return
	 */
	public static CharSequence getSpan(int color, float relative, int typeFace, CharSequence str) {
		SpannableStringBuilder sb = new SpannableStringBuilder(str);
		sb.setSpan(new ForegroundColorSpan(color), 0, sb.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
		if (relative != 1f) {
			sb.setSpan(new RelativeSizeSpan(relative), 0, sb.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
		}
		sb.setSpan(new StyleSpan(typeFace), 0, sb.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
		return sb;
	}

	/**
	 * @param context
	 *            获取veritoincode
	 * @return
	 */
	public static int getVersion() {
		int result = 0;
		try {
			PackageInfo info = WeijianzhiApplication.getInstance().getPackageManager().getPackageInfo(WeijianzhiApplication.getInstance().getPackageName(), 0);
			result = info.versionCode;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * @param context
	 *            获取版本名称
	 * @return
	 */
	public static String getVersionName() {
		String result = "";
		try {
			PackageInfo info = WeijianzhiApplication.getInstance().getPackageManager().getPackageInfo(WeijianzhiApplication.getInstance().getPackageName(), 0);
			result = info.versionName;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 获得可视高度
	 * 
	 * @param parent
	 * @param son
	 * @return
	 */
	public static int getVisiableHeight(ViewGroup parent, View son) {
		// parent 的可视区域
		/*
		 * parent.invalidate(); son.invalidate();
		 */
		Rect rect = new Rect();
		parent.getHitRect(rect);
		int offset = parent.getScrollY();
		int result = rect.height() - (son.getTop() - offset);
		return result;
	}

	public static String getSign(int num) {
		String result = "";
		if (num > 0) {
			result = "+";
		} else if (num == 0) {
			result = "";
		} else {
			result = "";
		}
		return result;
	}

	public static void gotoUrl(String url) {
		try {
			Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
			// 此处打开默认浏览器，若无默认浏览器则报错
			// intent.putExtra(Browser.EXTRA_APPLICATION_ID,
			// Base.getInstance().getPackageName());
			WeijianzhiApplication.getInstance().startActivity(intent);
		} catch (Exception e) {
			// e.printStackTrace();
			e.printStackTrace();
		}
	}

	public static Display display = null;

	public static Display getDisplay() {
		if (display == null) {
			WindowManager wm = ((Activity) WeijianzhiApplication.getInstance()).getWindowManager();
			display = wm.getDefaultDisplay();
		}
		return display;
	}

	public static int getScreenWidth() {
		return getDisplay().getWidth();
	}

	public static int getScreenHeight() {
		return getDisplay().getHeight();
	}

	/**
	 * 返回下一个元素，如果是最后一个，返回最后一个
	 * 
	 * @param <T>
	 * @param lists
	 * @param cur
	 * @return
	 */
	public static <T> T getNextCycle(List<T> lists, int cur) {
		int count = lists.size();
		T result;

		int next = cur + 1;

		if (next == count) {
			next = 0;
		}

		result = lists.get(next);

		return result;

	}

	public static Float max(Float... nums) {

		Float result = null;
		if (nums.length > 0) {
			result = nums[0];
			for (Float num : nums) {
				if (num > result) {
					result = num;
				}
			}
		}
		return result;
	}

	public static Float min(Float... nums) {

		Float result = null;
		if (nums.length > 0) {
			result = nums[0];
			for (Float num : nums) {
				if (num < result) {
					result = num;
				}
			}
		}
		return result;
	}

	public static Float sum(Float... nums) {

		Float result = 0f;
		for (Float num : nums) {
			result += num;
		}
		return result;
	}


	public static <T> ArrayList<T> toArrayList(T[] objects) {
		ArrayList<T> result = new ArrayList<T>();
		if (objects != null) {
			for (T object : objects) {
				result.add(object);
			}
		}
		return result;
	}

	public static String toString(InputStream inputStream) {
		BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
		StringBuilder total = new StringBuilder();
		try {
			String line;
			while ((line = r.readLine()) != null) {
				total.append(line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return total.toString();
	}

	// enum 类型
	/**
	 * enum to int
	 * 
	 * @param <E>
	 * @param type
	 * @return
	 */
	public static <E extends Enum<E>> int enumToInt(E type) {
		return type.ordinal();
	}

	/**
	 * int to enum
	 * 
	 * @param <E>
	 * @param clazz
	 * @param ordinal
	 * @return
	 */
	public static <E extends Enum<E>> E intToEnum(Class<E> clazz, int ordinal) {
		return clazz.getEnumConstants()[ordinal];

	}

	// 基于enum的 intentType设置
	public static <E extends Enum<E>> void setIntentType(Intent intent, E type) {
		intent.putExtra("INTENT_TYPE", enumToInt(type));
	}

	// 基于enum的 intentType获得
	public static <E extends Enum<E>> E getIntentType(Intent intent, Class<E> clazz) {
		int index = intent.getIntExtra("INTENT_TYPE", 0);
		E type = intToEnum(clazz, index);
		return type;
	}

	public static TextView getTextView(int id, View view) {
		return (TextView) view.findViewById(id);
	}

	public static <T extends Object> ArrayList<T> toArrayList(HashSet<T> hashSet) {
		ArrayList<T> result = new ArrayList<T>();
		if (hashSet != null) {

			result.addAll(hashSet);
		}
		return result;
	}

	public static int makeCrash() {
		int[] a = new int[4];
		return a[4];
	}

	public static String getStr(JSONObject jsonObject, String name) {
		String result = "";
		try {
			if (jsonObject != null && jsonObject.has(name)) {
				result = jsonObject.getString(name);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;

	}

	public static void startActivity(Intent intent) {
		if (intent != null) {
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			WeijianzhiApplication.getInstance().startActivity(intent);
		}
	}

	public static View getSpaceViewForListView(int width, int height) {

		View view = new TextView(WeijianzhiApplication.getInstance());
		view.setLayoutParams(new ListView.LayoutParams(width, height));
		return view;
	}

	/**
	 * 递归的回收view下的所有bitmap 建议运行在 Activity.onDestory()
	 * 
	 * @param view
	 */
	public static void recyleBitmapRecursively(final View view) {

		if (view != null) {
			view.setBackgroundDrawable(null);
		}
		if (view instanceof ImageView) {
			((ImageView) view).setImageDrawable(null);
		} else if (view instanceof ViewGroup) {
			int count = ((ViewGroup) view).getChildCount();
			for (int i = 0; i < count; i++) {
				recyleBitmapRecursively(((ViewGroup) view).getChildAt(i));
			}
		}

	}

	/**
	 * SharedPreferences 文件名
	 */
	private static final String SETTINGS = "settings";

	/**
	 * @param context
	 * @param key
	 * @param value
	 * @return 是否保存成功
	 */
	public static boolean setSharedPreferences(String key, String value) {
		SharedPreferences sp = WeijianzhiApplication.getInstance().getSharedPreferences(SETTINGS, Context.MODE_PRIVATE);
		return sp.edit().putString(key, value).commit();
	}

	/**
	 * @param context
	 * @param key
	 * @param defaultValue
	 * @return value
	 */
	public static String getSharedPreferences(String key, String defaultValue) {
		SharedPreferences sp = WeijianzhiApplication.getInstance().getSharedPreferences(SETTINGS, Context.MODE_PRIVATE);
		return sp.getString(key, defaultValue);
	}

	/**
	 * @param str
	 *            md5加密
	 * @return
	 */
	public static String md5s(String str) {
		if (str == null || str.length() == 0) {
			throw new IllegalArgumentException("String to encript cannot be null or zero length");
		}

		StringBuffer hexString = new StringBuffer();

		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(str.getBytes());
			byte[] hash = md.digest();
			int length = hash.length;
			for (int i = 0; i < length; i++) {
				if ((0xff & hash[i]) < 0x10) {
					hexString.append("0" + Integer.toHexString((0xFF & hash[i])));
				} else {
					hexString.append(Integer.toHexString(0xFF & hash[i]));
				}
			}
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}

		return hexString.toString();
	}

	/**
	 * 获取string
	 * 
	 * @param name
	 * @return
	 */
	public static String getStrValue(int id) {
		try {
			return WeijianzhiApplication.getInstance().getString(id);
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}

	/**
	 * 高清图与普通图相差大小
	 * 
	 * @param path
	 * @return
	 */
	public static long getSaveSize(String path) {
		File file = new File(path);
		long size = file.length();
		if (size == 0) {
			FileInputStream in = null;
			try {
				in = new FileInputStream(file);
				byte buffer[] = new byte[1024];
				size = 0;
				int num = 0;
				while ((num = in.read(buffer)) > 0) {
					size += num;
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (in != null) {
					try {
						in.close();
					} catch (Exception e2) {
						e2.printStackTrace();
					}
				}
			}
		}
		InputStream temp = null;
		try {
			temp = new FileInputStream(file);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		BitmapFactory.Options options = new BitmapFactory.Options();
		// 这个参数代表，不为bitmap分配内存空间，只记录一些该图片的信息（例如图片大小），说白了就是为了内存优化
		options.inJustDecodeBounds = true;
		// 通过创建图片的方式，取得options的内容（这里就是利用了java的地址传递来赋值）
		BitmapFactory.decodeStream(temp, null, options);
		int with = options.outWidth;
		int heigth = options.outHeight;
		int max = with > heigth ? with : heigth;
		float savePercent = 0;
		if (max > 1080 && max < 1600) {
			float px_percent_1 = ((float) (max * 1.0)) / with;
			float px_percent_2 = ((float) (1024 * 1.0)) / with;
			savePercent = (float) (px_percent_1 * px_percent_1 * 0.8 * 0.8 - px_percent_2 * px_percent_2 * 0.4);
		} else if (max >= 1600) {
			float px_percent_1 = ((float) (1600 * 1.0)) / with;
			float px_percent_2 = ((float) (1024 * 1.0)) / with;
			savePercent = (float) (px_percent_1 * px_percent_1 * 0.8 * 0.8 - px_percent_2 * px_percent_2 * 0.4);
		} else {
			savePercent = (float) 0.4;
		}
		return (long) (size * savePercent);
	}

	/***
	 * 指定大小的压缩
	 * 
	 * @param path
	 * @param limtMax
	 * @return
	 * @throws IOException
	 */
	private static Bitmap revitionImageSize(String path, int limtMax) throws IOException {
		// 取得图片
		File file = new File(path);
		InputStream temp = new FileInputStream(file);
		BitmapFactory.Options options = new BitmapFactory.Options();
		// 这个参数代表，不为bitmap分配内存空间，只记录一些该图片的信息（例如图片大小），说白了就是为了内存优化
		options.inJustDecodeBounds = true;
		// 通过创建图片的方式，取得options的内容（这里就是利用了java的地址传递来赋值）
		BitmapFactory.decodeStream(temp, null, options);
		// 关闭流
		temp.close();
		// 生成压缩的图片
		int i = 0;
		Bitmap bitmap = null;
		while (true) {
			// 这一步是根据要设置的大小，使宽和高都能满足
			if ((options.outWidth >> i <= limtMax) && (options.outHeight >> i <= limtMax)) {
				// 重新取得流，注意：这里一定要再次加载，不能二次使用之前的流！
				temp = new FileInputStream(file);
				// 这个参数表示 新生成的图片为原始图片的几分之一。
				options.inSampleSize = (int) Math.pow(2.0D, i);
				// 这里之前设置为了true，所以要改为false，否则就创建不出图片
				options.inJustDecodeBounds = false;
				options.inTargetDensity = 240;
				bitmap = BitmapFactory.decodeStream(temp, null, options);
				break;
			}
			i += 1;
		}
		return bitmap;
	}

	/**
	 * @param path
	 * @param limitMax
	 *            限制最大边
	 * @param quality
	 *            质量
	 * @return
	 */
	public static byte[] getAddBitmapByte(String path, int limitMax, int quality) {
		// 用于存储bitmap的字节数组
		int LIMIT_MAX_MARGIN = limitMax;
		byte[] data = null;
		Bitmap localBitmap = null;
		try {
			localBitmap = revitionImageSize(path, 2 * LIMIT_MAX_MARGIN);
		} catch (IOException e1) {
			e1.printStackTrace();
		}

		if (localBitmap != null) {
			int width = localBitmap.getWidth();
			int height = localBitmap.getHeight();
			if (width > LIMIT_MAX_MARGIN || height > LIMIT_MAX_MARGIN) {
				// 创建操作图片用的matrix对象
				Matrix matrix = new Matrix();
				// 计算宽高缩放率.
				float scaleWidth = 0;
				float scaleHeight = 0;
				int newWidth = 0;
				int newHeight = 0;
				if (width > height) {
					newWidth = LIMIT_MAX_MARGIN;
					newHeight = (LIMIT_MAX_MARGIN * height) / width;
					scaleWidth = ((float) newWidth) / width;
					scaleHeight = ((float) newHeight) / height;
				} else {
					newHeight = LIMIT_MAX_MARGIN;
					newWidth = (LIMIT_MAX_MARGIN * width) / height;
					scaleWidth = ((float) newWidth) / width;
					scaleHeight = ((float) newHeight) / height;
				}
				// 缩放图片动作
				matrix.postScale(scaleWidth, scaleHeight);
				// 创建缩放后的图片
				try {
					localBitmap = Bitmap.createBitmap(localBitmap, 0, 0, (int) width, (int) height, matrix, true);
				} catch (Exception e) {
					e.printStackTrace();
				} catch (OutOfMemoryError e) {
					e.printStackTrace();
				}
			}
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			// 压缩图片质量
			localBitmap.compress(CompressFormat.JPEG, quality, bos);
			data = bos.toByteArray();
			try {
				localBitmap.recycle();
				bos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return data;
	}

	/**
	 * 获取图片的旋转角度
	 * 
	 * @Title: readPictureDegree
	 * @param path
	 * @return int
	 */
	public static int readPictureDegree(String path) {
		int degree = 0;
		try {
			ExifInterface exifInterface = new ExifInterface(path);

			int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
			switch (orientation) {
			case ExifInterface.ORIENTATION_ROTATE_90:
				degree = 90;
				break;
			case ExifInterface.ORIENTATION_ROTATE_180:
				degree = 180;
				break;
			case ExifInterface.ORIENTATION_ROTATE_270:
				degree = 270;
				break;
			default:
				degree = 0;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return degree;
	}

	/**
	 * 旋转图片的bitmap角度
	 * 
	 * @param angle
	 * @param bitmap
	 * @return Bitmap
	 */
	public static Bitmap rotaingBitmap(int angle, Bitmap bitmap) {
		// 旋转图片 动作
		Matrix matrix = new Matrix();
		matrix.postRotate(angle);
		// 创建新的图片
		Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
		return resizedBitmap;
	}

	/**
	 * @param bmp
	 * @param radius
	 * @return
	 */
	public static Bitmap getCroppedBitmap(Bitmap bmp, float radius) {
		Bitmap sbmp;
		int width = (int) radius;
		if (bmp.getWidth() != width || bmp.getHeight() != width)
			sbmp = Bitmap.createScaledBitmap(bmp, width, width, false);
		else
			sbmp = bmp;
		Bitmap output = Bitmap.createBitmap(sbmp.getWidth(), sbmp.getHeight(), Config.ARGB_8888);
		Canvas canvas = new Canvas(output);

		final Paint paint = new Paint();
		final Rect rect = new Rect(0, 0, sbmp.getWidth(), sbmp.getHeight());

		paint.setAntiAlias(true);
		paint.setFilterBitmap(true);
		paint.setDither(true);
		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(Color.parseColor("#BAB399"));
		canvas.drawCircle(sbmp.getWidth() / 2 + 0.7f, sbmp.getHeight() / 2 + 0.7f, sbmp.getWidth() / 2 + 0.1f, paint);
		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		canvas.drawBitmap(sbmp, rect, rect, paint);
		return output;
	}

	public static View inflate(int id) {
		return LayoutInflater.from(WeijianzhiApplication.getInstance()).inflate(id, null);
	}


	/**
	 * 获取路径图片，缩放大小，返回缩放后的新bitmap
	 * 
	 * @param path
	 *            图片路径
	 * @param size
	 *            目标宽高
	 * @return
	 */
	public static Bitmap resizeBitmap(String path, int size) {
		Bitmap bitmap = BitmapFactory.decodeFile(path);
		return resizeBitmap(bitmap, size, size);
	}

	/**
	 * 对图片资源进行缩放之后返回新Bitmap
	 * 
	 * @param imgId
	 *            drawable id
	 * @param size
	 *            目标宽高，px
	 * @return 新bitmap
	 */
	public static Bitmap resizeBitmap(int imgId, int size) {
		Bitmap bitmap = BitmapFactory.decodeResource(WeijianzhiApplication.getInstance().getResources(), imgId);
		return resizeBitmap(bitmap, size, size);
	}

	/**
	 * 对bitmap进行缩放之后返回新Drawable
	 * 
	 * @param bitmap
	 *            源bitmap
	 * @param w
	 *            目标宽度
	 * @param h
	 *            目标高度
	 * @return 新bitmap
	 */
	public static Drawable resizeDrawable(Bitmap bitmap, int w, int h) {
		return new BitmapDrawable(resizeBitmap(bitmap, w, h));
	}

	/**
	 * 对bitmap进行缩放之后返回新bitmap
	 * 
	 * @param bitmap
	 *            源bitmap
	 * @param w
	 *            目标宽度, px
	 * @param h
	 *            目标高度, px
	 * @return 新bitmap
	 */
	public static Bitmap resizeBitmap(Bitmap srcBitmap, int w, int h) {
		if (srcBitmap == null) {
			return null;
		}
		int width = srcBitmap.getWidth();
		int height = srcBitmap.getHeight();
		int newWidth = w;
		int newHeight = h;

		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;

		Matrix matrix = new Matrix();
		matrix.postScale(scaleWidth, scaleHeight);

		return Bitmap.createBitmap(srcBitmap, 0, 0, width, height, matrix, true);
	}

	public static void importTempleData(BufferedInputStream in) {
		try {
			String path = WeijianzhiApplication.getInstance().getApplicationContext().getFilesDir().getAbsolutePath();

			path += "/" + "task.db";
			File file = new File(path);
			file.createNewFile();
			FileOutputStream outStream = new FileOutputStream(file);
			BufferedOutputStream out = new BufferedOutputStream(outStream);
			int c;
			while ((c = in.read()) >= 0) {
				out.write(c);
			}
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void startActivityForResult(Intent intent, int requestCode) {
		if (intent != null) {
			((Activity) WeijianzhiApplication.getInstance()).startActivityForResult(intent, requestCode);
			setActivityAnimation((Activity) WeijianzhiApplication.getInstance());
		}
	}

	/**
	 * activity间切换动画
	 * 
	 * @param activity
	 */
	public static void setActivityAnimation(Activity activity) {
		if (getIsSetAnimation()) {
			activity.overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
		}
	}

	public static boolean getIsSetAnimation() {
		return true;
	}

	/**
	 * 回收view的bitmap
	 * 
	 * @param view
	 */
	public static void recycleViewBitmap(View view) {
		if (view != null) {
			Drawable drawable = view.getBackground();
			if (drawable instanceof BitmapDrawable) {
				BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
				view.setBackgroundDrawable(null);
				drawable.setCallback(null);
				Bitmap bitmap = bitmapDrawable.getBitmap();
				if (bitmap != null) {
					if (!bitmap.isRecycled()) {
						bitmap.recycle();
					}
					bitmap = null;
				}
			}
		}

	}

	public static void DelData() {
		try {
			String path = WeijianzhiApplication.getInstance().getApplicationContext().getFilesDir().getAbsolutePath();

			path += "/" + "task.db";
			File file = new File(path);
			if (file.exists()) {
				file.delete();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static String encrypt(String input) throws Exception {
		return base64Encode(desEncrypt(input.getBytes()));
	}

	private static String base64Encode(byte[] s) {
		if (s == null)
			return null;

		return com.ihgoo.allinone.util.Base64.encodeBytes(s);
	}

	/**
	 * DES密钥
	 */
	private static final String private_key = "i*_uka*ld(_l);jsl;#k*&a";

	private static byte[] desEncrypt(byte[] plainText) throws Exception {
		SecureRandom sr = new SecureRandom();
		byte rawKeyData[] = private_key.getBytes();
		DESKeySpec dks = new DESKeySpec(rawKeyData);
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		SecretKey key = keyFactory.generateSecret(dks);
		Cipher cipher = Cipher.getInstance("DES");
		cipher.init(Cipher.ENCRYPT_MODE, key, sr);
		byte data[] = plainText;
		byte encryptedData[] = cipher.doFinal(data);
		return encryptedData;
	}

	/**
	 * 临时保存图片
	 * 
	 * @param bitmap
	 * @return 图片路径
	 */
	public static String saveImageToAPP(Bitmap bitmap) {
		String result = "";
		OutputStream out = null;
		try {
			if (bitmap != null) {
				String path = WeijianzhiApplication.getInstance().getApplicationContext().getFilesDir().getAbsolutePath();
				path = path + "/../.cache/";
				File file = new File(path);
				if (!file.exists()) {
					file.mkdir();
				}
				File cacheFile = new File(file, "imageShare.jpeg");
				cacheFile.deleteOnExit();
				out = new BufferedOutputStream(new FileOutputStream(cacheFile));
				bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
				result = cacheFile.getPath();
				// 文件关闭
				out.flush();
				out.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
			if (out != null) {
				try {
					out.flush();
					out.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
		return result;
	}

	public static Drawable getDrawable(String id) {
		int resourceId = -1;
		try {
			resourceId = getResourceId(id, "drawable");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return WeijianzhiApplication.getInstance().getResources().getDrawable(resourceId);
	}

	/**
	 * 手动回收imageView图片资源
	 * 
	 * @param imageView
	 */
	public static void releaseImageViewResouce(ImageView imageView) {
		if (imageView == null)
			return;
		Drawable drawable = imageView.getDrawable();
		if (drawable != null && drawable instanceof BitmapDrawable) {
			BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
			Bitmap bitmap = bitmapDrawable.getBitmap();
			if (bitmap != null && !bitmap.isRecycled()) {
				bitmap.recycle();
			}
		}
	}

	public static int dip2px(Context context, float dipValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dipValue * scale + 0.5f);
	}

	public static int px2dip(Context context, float pxValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}
	
	public static boolean notNull(String string){
		
		if("".equals(string) || string==null){
			return false;
		}else{
			return true;
		}
	}
	
	public static File createFile(){
		String pathimg = Environment.getExternalStorageDirectory().getPath()
				+ File.separator;
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
		Date date = new Date(System.currentTimeMillis());
		String filename = format.format(date);
		File outputimage = new File(pathimg, filename+".jpg");
		return outputimage;
	}
	
	public static String getToken(String str){
		String head ="";
		String last ="";
		String substring = str.substring(str.length()-10, str.length());//token后十位
		
	    	String substring4 = str.substring(0, str.length()-10);//去除后十位
		
		   String substring3 = substring4.substring(0, substring4.length()-15);//留取的
		   String substring2 = substring4.substring(substring4.length()-15, substring4.length());//待截取的
		
		for(int j=0;j<substring2.length();j++){
			if(j%3==0){
				head+=substring2.substring(j,++j);
			}
			if(j%3==1){
				last+=substring2.substring(j,++j);
			}
		}
		
		return head+substring3+substring+last;
	}
	
	public static ScaleInAnimationAdapter getMyadapter(BaseAdapter adapter,ListView lv){
		 ScaleInAnimationAdapter scaleInAnimationAdapter = new ScaleInAnimationAdapter(adapter, 0f);
		 scaleInAnimationAdapter.setListView(lv);
		 return scaleInAnimationAdapter;
	}
	
}
